#include <queue>
#include <pthread.h>

template <class T>
class BlockQueue
{
private:
    bool IsFull()
    {
        return _blockQueue.size() == _max;
    }

    bool IsEmpty()
    {
        return _blockQueue.empty();
    }

public:
    BlockQueue(int max = 5) : _max(max)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_condC, nullptr);
        pthread_cond_init(&_condP, nullptr);
    }

    // 消费者消费
    void Pop(T *out)
    {
        pthread_mutex_lock(&_mutex);
        while(IsEmpty())
        {
            pthread_cond_wait(&_condC, &_mutex);
        }
        *out = _blockQueue.front();
        _blockQueue.pop();
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_condP);
    }

    // 生产者生产
    void Equeue(const T &in)
    {
        pthread_mutex_lock(&_mutex);
        while (IsFull())
        {
            pthread_cond_wait(&_condP, &_mutex);
        }
        _blockQueue.push(in);
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_condC);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_condC);
        pthread_cond_destroy(&_condP);
    }

private:
    std::queue<T> _blockQueue;
    size_t _max;
    pthread_mutex_t _mutex;
    pthread_cond_t _condC;
    pthread_cond_t _condP;
};